#coding:utf-8
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils.html import strip_tags
import markdown 
from markdown_checklist.extension import ChecklistExtension
from datetime import datetime
# Create your models here.
# id自动创建
# https://www.zmrenwu.com/post/5/
class Category(models.Model):
	def __str__(self):
		return self.name
	name = models.CharField(max_length=100)


class Tag(models.Model):
	def __str__(self):
		return self.name
	name = models.CharField(max_length=100)

class Post(models.Model):
	def __str__(self):
		return self.title

	def get_author_url(self):
		if 'summer' in self.author.username:
			return reverse('blog:summer')
		elif 'magic' in self.author.username:
			return reverse('blog:magic')
		elif 'zengjia' in self.author.username:
			return reverse('blog:zengjia')
		elif 'yaojie' in self.author.username:
			return reverse('blog:yaojie')
		else:
			return reverse('blog:summer')

	def get_absolute_url(self):
		return reverse('blog:detail', kwargs={'pk': self.pk})

	def increase_views(self):
		self.views += 1
		self.save(update_fields=['views'])

	def save(self, *args, **kwargs):    
	# 如果没有填写摘要

		if not self.abstact:
		# 首先实例化一个 Markdown 类，用于渲染 body 的文本
			self.abstact = strip_tags(markdown.markdown(self.body,
								extensions=[
								'markdown.extensions.extra',
								'markdown.extensions.codehilite',
								'markdown.extensions.toc',
								'markdown_checklist.extension',
								]))[:54]
		# 先将 Markdown 文本渲染成 HTML 文本
		# strip_tags 去掉 HTML 文本的全部 HTML 标签
		# 从文本摘取前 54 个字符赋给 excerpt
		#self.abstact = strip_tags(md.convert(self.body))[:54]

		# 调用父类的 save 方法将数据保存到数据库中
		super(Post, self).save(*args, **kwargs)


	views = models.PositiveIntegerField(default = 0)

	title = models.CharField(max_length=100)

	body = models.TextField()

	created_time = models.DateTimeField(auto_now_add=True)

	modified_time = models.DateTimeField(auto_now=True)

	abstact = models.CharField(max_length=200, blank = True)

	category = models.ForeignKey(Category, on_delete=models.CASCADE)

	tags = models.ManyToManyField(Tag, blank=True)

	author = models.ForeignKey(User, on_delete=models.CASCADE)




